/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \personnelmanage\src\pages\QuotaManage\Report\InventoryDynamicReport\components\CompanyTab.tsx
 * @Date: 2022-01-13 15:30:31
 * @LastEditTime: 2022-11-04 09:57:58
 */

import React from 'react'
import { UdTable, UdFilter, http, UdToolbar, UdDatePicker } from '@/lib'
import UdSelect from '@/components/UdFormControls/UdSelect'
import quotaApis from '@/apis/AboutQuota'
import apis from '@/apis'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import dayjs from 'dayjs'
import { Button, Spin } from 'antd'
import { downBlobFile } from '@/utils/methods'
import moment from 'moment'
import isBetween from 'dayjs/plugin/isBetween'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
dayjs.extend(isBetween)
dayjs.extend(isSameOrBefore)
export default class CompanyTab extends React.Component<IProps, IState> {
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private brandList: any[] = this.props.brandList
  private tableProps: any = { rowKey: 'id', scroll: { x: true } }
  private conditions: any = [
    {
      label: '年份',
      id: 'year',
      initialValue: dayjs().year() + '',
      render: () => (
        <UdSelect
          options={this.state.yearList}
          allowClear={false}
          showSearch={true}
          optionFilterProp="children"
          onChange={value => this.handChangeYear(value)}
        />
      ),
    },
    {
      label: '日期',
      id: 'stageYearMonth',
      initialValue: moment(),
      render: () => (
        <UdDatePicker
          showToday={false}
          disabledDate={current => {
            return this.disabledDate(current)
          }}
        />
      ),
    },
    {
      label: '品牌公司',
      id: 'brandCode',
      initialValue: this.props.checkedCode,
      render: (
        <UdSelect
          showSearch
          allowClear={false}
          options={this.brandList}
          onChange={value => {
            this.changeBrandCode(value)
          }}
        />
      ),
    },
    {
      label: '物料分类',
      id: 'groupCode',
      render: () => <UdSelect allowClear={false} showSearch options={this.state.prodBarCodeList} />,
    },
  ]

  constructor(props) {
    super(props)
    this.state = {
      uploading: false,
      downloading: false,
      dataSource: [],
      page: 1,
      size: 10,
      total: 0,
      loading: false,
      yearList: [],
      prodBarCodeList: [],
      date: dayjs(),
    }
  }

  render() {
    const { date, uploading, downloading, loading } = this.state
    const dateStr = dayjs(date).format('YYYY年MM月DD日')
    let monthArr = this.getDiffMonth(date)
    const columns = [
      ['序号', 'id', (text, record, index) => index + 1, { width: '50px' }],
      { title: '品牌公司', dataIndex: 'brandName', minWidth: '50px', fixedWidth: '50px' },
      { title: '物料分类名称', dataIndex: 'groupName', minWidth: '180px', fixedWidth: '180px' },
      { title: '统计年份', dataIndex: 'stageMonth', minWidth: '50px', fixedWidth: '50px' },
      { title: `安全库存`, dataIndex: 'safeStock', minWidth: '80px', fixedWidth: '130px' },
      { title: `${dateStr}库存`, dataIndex: 'todayStock', minWidth: '150px', fixedWidth: '130px' },
      ...monthArr,
      { title: `截止到${dateStr}动销总量`, dataIndex: 'movingPinTotal', minWidth: '200px', fixedWidth: '200px' },
    ]
    return (
      <Spin spinning={uploading || downloading} tip={uploading ? '上传中，请稍后...' : '下载中，请稍后...'}>
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <Button type="primary" onClick={this.exportTableExcel}>
              导出
            </Button>
          }
        ></UdToolbar>
        <UdTable
          loading={loading}
          columns={columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChangePage}
          {...this.tableProps}
          pagination={{
            current: this.state.page,
            pageSize: this.state.size,
            total: this.state.total,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </Spin>
    )
  }

  componentDidMount() {
    this.getYearList()
    this.changeBrandCode(this.props.checkedCode, this.getTableData)
  }

  private getDiffMonth = (endDate: dayjs.Dayjs): ReadonlyArray<any> => {
    let monthArr = []
    let startMonth: any = `${endDate.year() - 1}-11-01`
    while (dayjs(startMonth).isSameOrBefore(endDate)) {
      let text = dayjs(startMonth).format('YYYY年MM月')
      let key = dayjs(startMonth).format('MM')
      monthArr.push({
        title: `${text}动销`,
        dataIndex: text,
        minWidth: '120px',
        fixedWidth: '120px',
        render: (text, record, index) => {
          return record.map[`${key}`]
        },
      })
      startMonth = dayjs(startMonth).add(1, 'month')
    }
    return monthArr
  }

  private disabledDate = (current: any): boolean => {
    const { year } = this.filterForm.getFieldsValue()
    return current && !dayjs(current).isBetween(`${year - 1}-11-01`, `${year}-${dayjs().month() + 1}-${dayjs().date() + 1}`, 'date', '[)')
  }

  private handChangeYear = (value): void => {
    this.filterForm.setFieldsValue({ stageYearMonth: moment().set('year', value) })
  }

  private exportTableExcel = (): void => {
    this.setState({ downloading: true })
    let params: Record<string, any> = { ...this.filterForm.getFieldsValue() }
    let { year, brandCode } = params
    let brandName = this.brandList.find(item => {
      return item.value === brandCode
    })?.title
    let stageYearMonth = params.stageYearMonth
    params['stageYearMonth'] = stageYearMonth ? dayjs(params.stageYearMonth).format('YYYY-MM-DD') : undefined
    params['type'] = 1
    delete params['year']
    http
      .post(quotaApis.downloadStockMoveActualTime, { ...params }, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(
            res.data,
            `${year - 1}-11-01-${moment(`${year}-10`).endOf('month').format('YYYY-MM-DD')}-${brandName}-动销实时报表`
          )
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private getYearList = (): void => {
    http.get(apis.GetQuotaAssessYearList).then(res => {
      const yearList = res.data?.map(({ year: value, name: title }) => ({ value: value + '', title })) || []
      this.setState({ yearList })
    })
  }

  private changeBrandCode = (value: any, callBack?: Function): void => {
    this.filterForm.setFieldsValue({ groupCode: undefined }, () => {
      this.setState({ prodBarCodeList: [] }, () => {
        Promise.allSettled([this.getProdBarList(value)]).then((res: any) => {
          this.setState(
            {
              prodBarCodeList: res[0]?.value || [],
            },
            () => {
              callBack && callBack()
            }
          )
        })
      })
    })
  }

  private getProdBarList = (value: any): Promise<any> => {
    return http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: value },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        return prodBarCodeList
      })
  }

  private handleChangePage = (pagination): void => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getTableData()
    })
  }

  private handleSearch = (values: any): void => {
    this.setState({ page: 1 }, () => {
      this.getTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils): void => {
    this.setState({ dataSource: [], page: 1, total: 0 }, () => {
      this.changeBrandCode(this.props.checkedCode, this.getTableData)
    })
  }

  private getTableData = async () => {
    this.setState({ loading: true })
    let params: Record<string, any> = { ...this.filterForm.getFieldsValue() }
    let stageYearMonth = params.stageYearMonth
    params['stageYearMonth'] = stageYearMonth ? dayjs(params.stageYearMonth).format('YYYY-MM-DD') : undefined
    params['type'] = 1
    delete params['year']
    try {
      let list: any = await http.post(quotaApis.stockMoveActualPage, {
        page: this.state.page,
        size: this.state.size,
        conditions: params,
      })
      const dataSource = list.data?.content

      this.setState({
        dataSource,
        page: list.data.number,
        size: list.data.size,
        total: list.data.totalElements,
        loading: false,
        date: dayjs(params.stageYearMonth),
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }
}

interface IProps {
  brandList: any[]
  checkedCode: number | string
}
interface IState {
  dataSource: any[]
  page: any
  size: any
  total: any
  loading: boolean
  prodBarCodeList: any[]
  yearList: []
  downloading: boolean
  uploading: boolean
  date: any
}
